# this script should live in service directory
import sys
import os

sys.path.append(".."+os.sep+os.sep+"service")
sys.path.append(".."+os.sep+os.sep+"swmm5ea")

"""Create a stand-alone executable"""

try:
    from guidata.disthelpers import Distribution
    import guidata.configtools as gc
except ImportError:
    raise ImportError, "This script requires guidata 1.4+"



import swmm_ea_controller as sc
from glob import glob
from os.path import dirname, basename

def create_executable():
    """Build executable using ``guidata.disthelpers``"""
    head=os.path.join("..","swmm5ea")
    #lst=[glob(os.path.join(head,x)) for x in sc.LIST_OF_FILE_GLOBS]
    #lst=[item for sublist in lst for item in sublist]
    #data_files=[[dirname(x)[13:],[x]] for x in lst]
    
    cwd=os.path.abspath(os.path.join(os.getcwd(),"..","swmm5ea"))
    data_files=[[
        os.path.dirname(x[len(cwd)+1:]),
        [os.path.join("..","swmm5ea",x[len(cwd)+1:])]
        ] for x in sc.LIST_OF_FILE_GLOBS ]  
    
    for i in data_files:
        print i
    #raw_input()    
    dist = Distribution()
    dist.setup( name=sc.NAME, version=sc.VERSION,
               description=sc.DESCRIPTION,
               script="..\swmm5ea\swmm5ec_.pyw", target_name=sc.TARGET,
    icon="../res/DNA.ico",
    data_files=data_files)

    dist.add_modules('guidata', 'guiqwt')
    # Building executable
    dist.build('cx_Freeze')
    
def create_setupscript():
    template=r"""; Script generated by the Inno Setup Script Wizard.
    ; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!
    
    #define MyAppName "%(name)s"
    #define MyAppVersion "%(version)s"
    #define MyAppPublisher "%(publisher)s"
    #define MyAppURL "%(url)s"
    #define MyAppExeName "%(exename)s"
    #define MyOutputBaseName "%(outputbasename)s"
    
    
    [Setup]
    ; NOTE: The value of AppId uniquely identifies this application.
    ; Do not use the same AppId value in installers for other applications.
    ; (To generate a new GUID, click Tools | Generate GUID inside the IDE.)
    AppId={{92A4F79D-E285-4878-AA00-81E16CAE3650}
    AppName={#MyAppName}
    AppVersion={#MyAppVersion}
    ;AppVerName={#MyAppName} {#MyAppVersion}
    AppPublisher={#MyAppPublisher}
    AppPublisherURL={#MyAppURL}
    AppSupportURL={#MyAppURL}
    AppUpdatesURL={#MyAppURL}
    DefaultDirName={pf}\{#MyAppName}
    DefaultGroupName={#MyAppName}
    AllowNoIcons=yes
    LicenseFile=%(p)sCOPYING.txt
    InfoBeforeFile=%(p3)sREADME.txt
    InfoAfterFile=POSTINSTALL.txt
    OutputBaseFilename={#MyOutputBaseName}
    SetupIconFile=%(p2)sDNA.ico
    Compression=lzma
    SolidCompression=yes
    
    [Languages]
    Name: "english"; MessagesFile: "compiler:Default.isl"
    
    [Tasks]
    Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked
    Name: "quicklaunchicon"; Description: "{cm:CreateQuickLaunchIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked; OnlyBelowVersion: 0,6.1
    
    [Files]
    Source: "dist\swmm5ec.exe"; DestDir: "{app}"; Flags: ignoreversion
    ; NOTE: Don't use "Flags: ignoreversion" on any shared system files
    Source: "dist\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
    
    [Icons]
    Name: "{group}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"
    Name: "{group}\{cm:ProgramOnTheWeb,{#MyAppName}}"; Filename: "{#MyAppURL}"
    Name: "{group}\{#MyAppName}-Examples"; Filename: "{app}\examples"
    Name: "{group}\{#MyAppName}-Users' Guide"; Filename: "{app}\doc\_build\html\index.html"
    Name: "{group}\{cm:UninstallProgram,{#MyAppName}}"; Filename: "{uninstallexe}"
    Name: "{commondesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Tasks: desktopicon
    Name: "{userappdata}\Microsoft\Internet Explorer\Quick Launch\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Tasks: quicklaunchicon
    
    [Run]
    Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent
    """ 
    
    f=open("install.iss","w")
    import swmm_ea_controller as sc

    f.write(template % { "name" : sc.NAME
                        ,"version": sc.VERSION
                        ,"publisher": sc.PUBLISHER
                        ,"url": sc.URL
                        ,"exename": sc.TARGET, 
                        "outputbasename": sc.SETUPNAME, 
                        "p": ".."+os.sep+"swmm5ea"+os.sep, 
                        "p2": ".."+os.sep+"res"+os.sep,
                        "p3": ".."+os.sep})
    f.close()

def run_innosetup():
    import subprocess
    subprocess.call(['c:\\Program Files (x86)\\Inno Setup 5\\ISCC.exe', 'install.iss'])


if __name__ == '__main__':
    create_executable()
    create_setupscript()
    run_innosetup()
